#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QComboBox>
#include <QFontComboBox>
#include <QLabel>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextCharFormat>
#include <QAbstractItemView>
#include <QPushButton>
#include <QColorDialog>
#include <QPalette>

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QSize curSize = event->size();
    qDebug() << curSize.height() << curSize.width();
    int newWidth = curSize.width();
    int newHeight = ui->centralwidget->height();
    QSize textEditSize(newWidth, newHeight);
//    qDebug() << ui->centralwidget->height();
    ui->textEdit->resize(textEditSize);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->m_curFile = nullptr;
    this->m_curDir = "/home/lxy/Desktop/textEdit_demo/";
    initUi();

}

// 工具栏、状态栏
void MainWindow::initUi()
{
    // 调整窗口主体位置
    this->move(500, 300);

    // 设置右键菜单不可用
    this->setContextMenuPolicy(Qt::NoContextMenu);

    /* 设置第二行工具栏 */
    // 添加两行工具栏需要设置break
    this->addToolBarBreak(Qt::TopToolBarArea);
    m_tb = new QToolBar(this);
    this->addToolBar(m_tb);
    // 添加字号下拉框
    QLabel* sizeLabel = new QLabel("字号：", this);
    QFont ft;   // 显示“字号、字体”的格式，后续还会用
    ft.setPointSize(14);
    sizeLabel->setFont(ft);
    m_tb->addWidget(sizeLabel);
    m_sizeBox = new QComboBox(this);
    m_sizeBox->setEditable(true);   // 为了让下面效果生效
    m_sizeBox->setMaxVisibleItems(10);
    m_sizeBox->setFixedWidth(60);
    m_tb->addWidget(m_sizeBox);
    QStringList sizes;  // 添加字号 10-96
    for (int i = 5; i <= 48; ++i)
    {
        sizes << QString::number(2 * i);
    }
    m_sizeBox->addItems(sizes);
    // 获取当前字号并设置字号下拉框
    m_sizeBox->setCurrentText(QString::number(ui->textEdit->font().pointSize()));
    // 字号下拉框改变，字体发生相应改变
    connect(m_sizeBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index){
        QString curStr = m_sizeBox->currentText();
        int i = curStr.toInt();
        if (i > 0 && i < 100)
        {
//            qDebug() << i;
            QTextCharFormat fmt = ui->textEdit->currentCharFormat();
            fmt.setFontPointSize(i);
            ui->textEdit->mergeCurrentCharFormat(fmt);
        }
    });

    // 添加字体下拉框
    QLabel* fontLabel = new QLabel("  字体：", this);
    fontLabel->setFont(ft);
    m_tb->addWidget(fontLabel);
    m_fontBox = new QFontComboBox(this);
    m_tb->addWidget(m_fontBox);
    connect(m_fontBox, &QFontComboBox::currentFontChanged, this, [=](QFont f){
        QTextCharFormat fmt = ui->textEdit->currentCharFormat();
        fmt.setFontFamily(f.family());
//        qDebug() << f.family();
        ui->textEdit->mergeCurrentCharFormat(fmt);
    });

    /* 颜色按钮 */
    m_tb->addSeparator();
    m_curColor = QColor(Qt::black);
//    qDebug() << m_curColor;
    m_setColorBtn = new QPushButton(this);
    m_setColorBtn->setFixedSize(20, 20);
    QPalette pal;   // 给按钮设置背景色
    pal.setColor(QPalette::Button, m_curColor);
    m_setColorBtn->setPalette(pal);
    m_setColorBtn->setAutoFillBackground(true);
    m_setColorBtn->setFlat(true);
    m_tb->addWidget(m_setColorBtn);
    // 点击设置颜色按钮
    connect(m_setColorBtn, &QPushButton::clicked, this, [=](){
        QTextCharFormat fmt = ui->textEdit->currentCharFormat();
        fmt.setForeground(m_curColor);
        ui->textEdit->mergeCurrentCharFormat(fmt);
    });
    QPushButton* chooseColorBtn = new QPushButton("选择颜色", this);
                                                  m_tb->addWidget(chooseColorBtn);
    // 颜色选择对话框
    QColorDialog* colorBoard = new QColorDialog(this);
    colorBoard->setOption(QColorDialog::ShowAlphaChannel);
    // 选择完颜色后，设置颜色按钮会变色
    connect(chooseColorBtn, &QPushButton::clicked, this, [=](){
        colorBoard->show();
        connect(colorBoard, &QColorDialog::colorSelected, this, [=](QColor curColor){
//            qDebug() << curColor;
            m_curColor = curColor;
            QPalette pal;
            pal.setColor(QPalette::Button, m_curColor);
            m_setColorBtn->setPalette(pal);
            QTextCharFormat fmt = ui->textEdit->currentCharFormat();
            fmt.setForeground(m_curColor);
            ui->textEdit->mergeCurrentCharFormat(fmt);

        });
    });


    /* 设置底部状态栏 */
    QString locText = QString(" 行：%1，列：%2").arg(1).arg(1);
    m_locShow = new QLabel(locText, this);
    ui->statusBar->addWidget(m_locShow);

    int all = ui->textEdit->toPlainText().length();
    QString numStr = QString("字数：%1").arg(all);
    m_charNums = new QLabel(numStr, this);
    ui->statusBar->addPermanentWidget(m_charNums);
}

MainWindow::~MainWindow()
{
    delete ui;
    if (this->m_curFile)
    {
        delete m_curFile;
    }
}

// 新建文件
bool MainWindow::createFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, "文件打开对话框", m_curDir, "lxy文件(*.lxy)");
    if (fileName == "")
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("温馨提示");
        msgBox.setText("选择文件失败！");
        msgBox.setStandardButtons(QMessageBox::Yes);
        msgBox.exec();
        return false;
    }
    if (!fileName.endsWith(".lxy"))
    {
        fileName += ".lxy";
    }
    qDebug() << fileName;
    m_curFile = new QFile(fileName);
    if (!m_curFile) // 内存分配失败
    {
        qDebug() << "create QFile failed.";
        return false;
    }
    if (!m_curFile->open(QIODevice::WriteOnly | QIODevice::Text)) // 打开文件失败
    {
        qDebug() << "file create failed";
        return false;
    }
    m_curFile->close();

    return true;
}

// 设置保存文件
void MainWindow::on_saveFileAction_triggered()
{
    qDebug() << "click save file btn";
    QTextDocument* doc = ui->textEdit->document();

//    qDebug() << doc->toHtml();
    if (!m_curFile) // 没有文件位置
    {
        if (!createFile())  // 创建文件失败
        {
            return;
        }
    }
    if (!m_curFile->open(QIODevice::WriteOnly | QIODevice::Text)) // 打开文件失败
    {
        qDebug() << "file create failed";
        exit(-1);
    }
    QTextStream ts(m_curFile);
    ts << doc->toHtml();
    qDebug() << doc->toHtml();
    m_curFile->close();

}

// 设置打开文件
void MainWindow::on_OpenFileAction_triggered()
{
    if (m_curFile)  // 已经存在一个文件
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("温馨提示");
        msgBox.setText("您已打开一个文件！");
        msgBox.setStandardButtons(QMessageBox::Yes);
        msgBox.exec();
        return;
    }
    QString fileName = QFileDialog::getOpenFileName(this, "文件打开对话框", m_curDir, "lxy文件(*.lxy)");
    qDebug() << fileName;
    if (fileName == "")
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("温馨提示");
        msgBox.setText("打开文件失败！");
//        msgBox.setInformativeText("Do you want to save your changes?");
        msgBox.setStandardButtons(QMessageBox::Yes);
        msgBox.exec();
        return;
    }
    m_curFile = new QFile(fileName);
    if (!m_curFile) // 内存分配失败
    {
        qDebug() << "create QFile failed.";
        return;
    }
    if (!m_curFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "open file failed.";
        return;
    }
    QTextStream ts(m_curFile);
    QString str = ts.readAll();
    ui->textEdit->setHtml(str);
    m_curFile->close();
}

// 设置加粗
void MainWindow::on_boldAction_triggered(bool checked)
{
    QTextCursor cursor = ui->textEdit->textCursor();
//    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat fmt = ui->textEdit->currentCharFormat();
//    bool isItalic = fmt.fontItalic();
//    bool isUnderline = fmt.fontUnderline();
//    qDebug() << isItalic << isUnderline;
    fmt.setFontItalic(ui->italicAction->isChecked());
    fmt.setFontUnderline(ui->underlineAction->isChecked());
    fmt.setFontWeight(checked ? QFont::Bold: QFont::Normal);
    ui->textEdit->mergeCurrentCharFormat(fmt);
    cursor.setCharFormat(fmt);
}

// 设置下划线
void MainWindow::on_underlineAction_triggered(bool checked)
{
    QTextCursor cursor = ui->textEdit->textCursor();
//    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat fmt = ui->textEdit->currentCharFormat();
    fmt.setFontUnderline(checked);
    fmt.setFontItalic(ui->italicAction->isChecked());
    fmt.setFontWeight(ui->boldAction->isChecked()? QFont::Bold: QFont::Normal);
    ui->textEdit->mergeCurrentCharFormat(fmt);
    cursor.setCharFormat(fmt);
}

// 设置斜体
void MainWindow::on_italicAction_triggered(bool checked)
{
    QTextCursor cursor = ui->textEdit->textCursor();
//    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat fmt = ui->textEdit->currentCharFormat();
    fmt.setFontItalic(checked);
    fmt.setFontUnderline(ui->underlineAction->isChecked());
    fmt.setFontWeight(ui->boldAction->isChecked()? QFont::Bold: QFont::Normal);
    ui->textEdit->mergeCurrentCharFormat(fmt);
    cursor.setCharFormat(fmt);
}

// 鼠标选择位置变化
void MainWindow::on_textEdit_selectionChanged()
{
//    static int i = 0;
//    qDebug() << ++i << " selection changed";
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextCharFormat fmt = cursor.charFormat();

    // 查看当前选中区域是否有特殊效果
    ui->boldAction->setChecked(fmt.fontWeight() == QFont::Bold);
    ui->underlineAction->setChecked(fmt.fontUnderline());
    ui->italicAction->setChecked(fmt.fontItalic());
    QTextBlockFormat bfmt = cursor.blockFormat();
    ui->leftAction->setChecked(bfmt.alignment() == Qt::AlignLeft);
    ui->centerAction->setChecked(bfmt.alignment() == Qt::AlignCenter);
    ui->rightAction->setChecked(bfmt.alignment() == Qt::AlignRight);
    ui->justifyAction->setChecked(bfmt.alignment() == Qt::AlignJustify);

    /* 第二行工具栏，字号字体、颜色 */
//    qDebug() << fmt.fontPointSize();
    m_sizeBox->setCurrentText(QString::number(fmt.fontPointSize()));
//    qDebug() << fmt.fontFamily();
    m_fontBox->setCurrentText(fmt.fontFamily());
    QBrush bru = ui->textEdit->currentCharFormat().foreground();
    m_curColor = bru.color();
    QPalette pal;
    pal.setColor(QPalette::Button, m_curColor);
    m_setColorBtn->setPalette(pal);

    /* 底部状态栏 */
    int row = 1, col = 1;
    calRowCol(row, col);
    QString locText = QString(" 行：%1，列：%2").arg(row).arg(col);
    m_locShow->setText(locText);
    int all = ui->textEdit->toPlainText().length();
    if (cursor.hasSelection())
    {
//        qDebug() << "hasselection";
        int cur = cursor.selectedText().length();
//        qDebug() << cur << "/" << all;
        QString numStr = QString("字数：%1/%2").arg(cur).arg(all);
        m_charNums->setText(numStr);
    }
    else
    {
        QString numStr = QString("字数：%1").arg(all);
        m_charNums->setText(numStr);
    }

}

// 计算鼠标行列
void MainWindow::calRowCol(int& row, int& col)
{
    QString text = ui->textEdit->toPlainText();
    int curCharNum = ui->textEdit->textCursor().position();
    for (int i = 0; i < curCharNum; ++i)
    {
        if (text[i] == '\n')
        {
            ++row;
            col = 0;
        }
        ++col;
    }
}

// 设置左对齐
void MainWindow::on_leftAction_triggered(bool checked)
{
    if (!checked)   // 选中状态再点无效
    {
        ui->leftAction->setChecked(true);
//        return;
    }
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextBlockFormat fmt = cursor.blockFormat();
    fmt.setAlignment(Qt::AlignLeft);
    cursor.mergeBlockFormat(fmt);

    ui->centerAction->setChecked(false);
    ui->rightAction->setChecked(false);
    ui->justifyAction->setChecked(false);
}

// 设置居中对齐
void MainWindow::on_centerAction_triggered(bool checked)
{
    if (!checked)   // 选中状态再点无效
    {
        ui->centerAction->setChecked(true);
//        return;
    }
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextBlockFormat fmt = cursor.blockFormat();
    fmt.setAlignment(Qt::AlignCenter);
    cursor.mergeBlockFormat(fmt);
    ui->leftAction->setChecked(false);
    ui->rightAction->setChecked(false);
    ui->justifyAction->setChecked(false);
}

// 设置右对齐
void MainWindow::on_rightAction_triggered(bool checked)
{
    if (!checked)   // 选中状态再点无效
    {
        ui->rightAction->setChecked(true);
//        return;
    }
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextBlockFormat fmt = cursor.blockFormat();
    fmt.setAlignment(Qt::AlignRight);
    cursor.mergeBlockFormat(fmt);
    ui->leftAction->setChecked(false);
    ui->centerAction->setChecked(false);
    ui->justifyAction->setChecked(false);
}

// 设置两端对齐
void MainWindow::on_justifyAction_triggered(bool checked)
{
    if (!checked)   // 选中状态再点无效
    {
        ui->justifyAction->setChecked(true);
//        return;
    }
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextBlockFormat fmt = cursor.blockFormat();
    fmt.setAlignment(Qt::AlignJustify);
    cursor.mergeBlockFormat(fmt);
    ui->leftAction->setChecked(false);
    ui->centerAction->setChecked(false);
    ui->rightAction->setChecked(false);
}

// 新建文件
void MainWindow::on_newFileAction_triggered(bool checked)
{
    m_curFile = nullptr;
    createFile();
}

